<template>
<!--  竞赛页面展示的子竞赛-->
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="竞赛名称" prop="name" style="margin-left: 22px">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入竞赛名称"
          clearable
          @keyup.enter.native="handleQuery"
          style="width: 139px"
        />
      </el-form-item>
      <el-form-item label="年度" prop="year">
        <el-date-picker
          clearable
          v-model="queryParams.year"
          type="year"
          value-format="yyyy"
          placeholder="请选择年度"
          :picker-options="pickerOptions"
          style="width: 130px">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="级别" prop="rank">
        <el-select v-model="queryParams.level" placeholder="全部" clearable style="width: 125px">
          <el-option
            v-for="dict in dict.type.sub_contest_rank"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="delFlag">
        <el-select v-model="queryParams.delFlag" placeholder="全部" clearable style="width: 125px">
          <el-option
            v-for="dict in dict.type.sys_normal_disable"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item style="">
        <el-button type="primary" icon="el-icon-search" size="mini"
                   @click="handleQuery" style="height: 30px">搜索
        </el-button>
        <el-button icon="el-icon-refresh" size="mini"
                   @click="resetQuery" style="height: 30px">重置
        </el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['contest:subContest:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['contest:subContest:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['contest:subContest:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['contest:subContest:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="subContestList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="竞赛名称" align="center" prop="name" />
      <el-table-column label="竞赛通知网址" align="center" prop="url"/>
      <el-table-column label="附件" align="center" prop="attachmentsUrl" width="90">
        <template slot-scope="scope">
          <span v-if="scope.row.attachmentsUrl != null"
                v-bind:class="sliceFileName(scope.row.attachmentsUrl)">
            {{slice_file}}
          </span>
          <span v-else>暂无</span>
        </template>
      </el-table-column>
      <el-table-column label="年度" align="center" prop="year" width="60">
      </el-table-column>
      <el-table-column label="级别" align="center" prop="level" width="98">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sub_contest_rank" :value="scope.row.level"/>
        </template>
      </el-table-column>
      <el-table-column label="竞赛日期" align="center" prop="competitionDate" width="95">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.competitionDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="报名费用" align="center" prop="fee" width="80"/>
      <el-table-column label="启用状态" align="center" prop="delFlag" width="72">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.delFlag"
            active-color="#ff4949"
            inactive-color="#13ce66"
            active-value="1"
            inactive-value="0"
            @change="changeSubState(scope.row)"
          >
          </el-switch>
        </template>

      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="70">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['contest:subContest:edit']"
            style="margin-right: 3px;margin-left: 1px;font-size: 16px"
          ></el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['contest:subContest:remove']"
            style="margin-left: 3px;font-size: 16px"
          ></el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改子竞赛信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-row>
        <el-form ref="form" :model="form" :rules="rules" label-width="100px">
          <el-col>
            <el-form-item label="竞赛名称" prop="name" style="margin-bottom: 12px">
              <el-input v-model="form.name" placeholder="请输入竞赛名称"/>
            </el-form-item>
          </el-col>
          <el-col>
            <el-form-item label="竞赛通知网址" prop="url" style="margin-bottom: 12px">
              <el-input v-model="form.url" placeholder="请输入竞赛通知网址"/>
            </el-form-item>
          </el-col>
          <el-col>
            <el-form-item label="上传附件" prop="attachmentsUrl" style="margin-bottom: 12px">
              <file-upload v-model="form.attachmentsUrl" @fileInfo="handleFileInfo"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="年度" prop="year" style="margin-bottom: 12px">
              <el-select v-model="form.year" clearable placeholder="请选择年度" style="width: 132px">
                <el-option
                  v-for="(item,i) in years"
                  :key="i"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="竞赛日期" prop="competitionDate" style="margin-bottom: 12px;margin-left: 60px">
              <el-date-picker clearable
                              style="width: 145px;margin-left: 1px"
                              v-model="form.competitionDate"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="请选择日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="级别" prop="level" style="margin-bottom: 12px">
              <el-select v-model="form.level" placeholder="全部" style="width: 133px">
                <el-option
                  v-for="dict in dict.type.sub_contest_rank"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="报名费用" prop="fee" style="margin-bottom: 12px;margin-left: -17px">
              <el-input v-model="form.fee" placeholder="请输入报名费用" style="width: 145px"/>
            </el-form-item>
          </el-col>
          <el-col>
            <el-form-item label="备注" prop="remark" style="margin-bottom: 12px">
              <el-input v-model="form.remark" placeholder="请输入备注"/>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listSubContest,
  getSubContest,
  delSubContest,
  addSubContest,
  updateSubContest,
  changeSubEnable
} from "@/api/contest/subContest";
import item from "@/layout/components/Sidebar/Item.vue";
import {switchState} from "@/api/contest/contestInfo";

import UploadfileItem from "@/components/UploadfileItem";
import {getToken} from "@/utils/auth";

export default {
  name: "indexmini",
  //刷新
  inject: ['reload'],
  dicts: ['sys_normal_disable', 'sub_contest_rank'],
  data() {
    return {
      // 年份不能大于当前时间
      pickerOptions:{
        disabledDate(time) {
          //如果没有后面的-8.64e7就是不可以选择今天的
          return time.getTime() > Date.now() - 8.64e7;
        }
      },
      //当前时间的前15年年度
      years:[],
      // 接收传入的值
      contestInfoVale: 0,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 选中的数组名称
      subContestNamesList: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 子竞赛信息表格数据
      subContestList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        contestId: null,
        name: null,
        year: null,
        level: null,
        delFlag: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      //文件名
      file_name:"",
      slice_file:"",
    };
  },
  components:{
    UploadfileItem
  },
  created() {
    // 接收传入的值
    this.$bus.on("pass item", value => {
      this.contestInfoVale = value; // value为从contestInfo中传入的值
      this.getList();
    })
  },
  mounted() {
    this.getYear();
  },
  methods: {
    //正则切割文件名
    sliceFileName(fileName){
      var nstr = fileName.split(/[/,_,.]/)
      var miniNstr = nstr[nstr.length-3] +"." + nstr[nstr.length-1]
      this.slice_file = miniNstr
    },
    //文件信息
    handleFileInfo(val) {
      this.fileList = val
    },
    /** 查询子竞赛信息列表 */
    getList() {
      this.loading = true;

      //将contestInfo组件传入的值进行赋值
      this.queryParams.contestId = this.contestInfoVale;

      listSubContest(this.queryParams).then(response => {
        this.subContestList = response.rows;
        console.log(this.subContestList)
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.reload();
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        subContestId: null,
        contestId: null,
        name: null,
        url: null,
        attachmentsUrl: null,
        year: null,
        level: null,
        competitionDate: null,
        fee: null,
        remark: null,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.subContestId)
      this.subContestNamesList =  selection.map(item => item.name)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加子竞赛信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const subContestId = row.subContestId || this.ids
      getSubContest(subContestId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改子竞赛信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.form.contestId = this.contestInfoVale
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.subContestId != null) {
            updateSubContest(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addSubContest(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
      this.$refs.upload.submit();
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const subContestIds = row.subContestId || this.ids;
      const subContestName = row.name || this.subContestNamesList;
      this.$modal.confirm('是否确认删除名称为 " ' + subContestName + ' " 的子竞赛信息？此操作将永久删除数据库内容，请咨询技术人员后操作！').then(function () {
        return delSubContest(subContestIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('contest/subContest/export', {
        ...this.queryParams
      }, `subContest_${new Date().getTime()}.xlsx`)
    },
    //获取年份
    getYear(){
      var y = new Date().getFullYear();
      for(var i = 0;i <= 15;i ++){
        if(i < 15){
          this.years.unshift({value: (y - i),label: (y - i)})
        }
      }
    },
    //更改状态按钮
    changeSubState(row){
      const subContestIds = row.subContestId;
      const subContestName = row.name;
      var flags;
      row.delFlag === "0" ? flags = '启用' : flags = '禁用';
      let subSwitchInfo = {
        delFlag: row.delFlag,
        subContestId: subContestIds
      }
      this.$modal.confirm('是否确认将 " ' + subContestName + ' " 子竞赛' + flags + '？').then(function () {
        return changeSubEnable(subSwitchInfo)
      }).then(()=>{
        this.getList()
        this.$modal.msgSuccess("修改成功")
      }).catch(() => {
        this.getList();
      });
    },
  },

};
</script>
